package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.ClassBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class JsonServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("servlet初始化");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        List<ClassBean> list = new ArrayList<>();
        list.add(new ClassBean(2,"高中一班", LocalDate.parse("2019-03-04")));
        list.add(new ClassBean(3,"高中二班", LocalDate.parse("2019-03-08")));
        list.add(new ClassBean(6,"高中三班", LocalDate.parse("2019-03-11")));
        list.add(new ClassBean(8,"高中四班", LocalDate.parse("2019-03-15")));

        ObjectMapper om = new ObjectMapper();
        //添加日期格式支持
        om.registerModule(new JavaTimeModule());
        //将对象转化为 json字符串
        String str = om.writeValueAsString(list);
        resp.getWriter().print(str);
    }
}
